package racing.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import racing.client.ChatClient;
import racing.client.Client;

/**
 * 
 * 
 * @author Sarathit Sangtaweep 5510546182
 * @author Veerapat Teeravipark 5510547022
 * @version 2013
 */
public class ConnectUI extends JFrame{

	private static final long serialVersionUID = 1L;
	private RacingUI ui;
	private ChatUI chatui;
	private Client client;
	private ChatClient chatClient;
	JButton connect_button;
	JTextField ip_text;
	JLabel ip_label;

	/**
	 * 
	 * @param ui
	 * @param chatui
	 */
	public ConnectUI(RacingUI ui, ChatUI chatui) {
		this.ui = ui;
		this.chatui = chatui;
		getContentPane().setLayout(null);
		initComponent();
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}

	/**
	 * 
	 */
	private void initComponent() {
		connect_button = new JButton();
		connect_button.setLocation(262, 23);
		connect_button.setSize(100, 30);
		connect_button.setText("Connect");
		connect_button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				client = new Client(ip_text.getText(), 16668);
				chatClient = new ChatClient(ip_text.getText(), 16669);
				try {
					client.openConnection();
					chatClient.openConnection();
				} catch (IOException e) {
					JOptionPane.showMessageDialog(null, "Server closed.",
							"Announce", JOptionPane.WARNING_MESSAGE);
				}
				if (client.isConnected() && chatClient.isConnected()) {
					JOptionPane.showMessageDialog(null, "Success", "Announce",
							JOptionPane.WARNING_MESSAGE);
					ui.setClient(client);
					chatui.setClient(chatClient);
					dispose();
				}
			}
		});
		getContentPane().add(connect_button);
		getRootPane().setDefaultButton(connect_button);

		ip_text = new JTextField();
		ip_text.setLocation(85, 23);
		ip_text.setSize(150, 30);
		ip_text.setText("");
		getContentPane().add(ip_text);

		ip_label = new JLabel();
		ip_label.setLocation(30, 23);
		ip_label.setSize(40, 30);
		ip_label.setText("IP :");
		getContentPane().add(ip_label);

		setTitle("Connect Server");
		setSize(396, 115);

	}

	/**
	 * 
	 */
	public void run() {
		pack();
		setVisible(true);
	}

}
